package com.frkj.yuan.activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.frkj.yuan.R;
import com.frkj.yuan.api.bean.MapPoiListBean;
import com.frkj.yuan.api.category.MapPoiCategory;
import com.frkj.yuan.api.presenter.MapPoiPresenter;
import com.frkj.yuan.main.ConstantStaticUrl;
import com.frkj.yuan.utils.FullScreenUtils;
import com.frkj.yuan.utils.SensorEventHelper;
import com.frkj.yuan.utils.ToastUtil;
import com.larissa.waveview.WaveView;

import cn.ycbjie.ycstatusbarlib.bar.YCAppBar;

/**
 * 信息说明:
 * company: 兰州丰荣信息科技有限公司
 * 创建时间: on 2022/4/21 16 ：13
 * 项目名称：yuanban
 */
public class MapPoiActvity extends AppCompatActivity implements LocationSource, AMapLocationListener,MapPoiCategory.View, View.OnClickListener {
    private AMap aMap;
    private MapView mapView;
    private SensorEventHelper mSensorHelper;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);
    private boolean mFirstFix = false;
    private Marker mLocMarker;
    private Circle mCircle;
    public static final String LOCATION_MARKER_FLAG = "mylocation";
    private CameraUpdate mUpdata;
    private LatLng latLng = new LatLng(36.05432, 103.873588);
    private MarkerOptions markerOption;
    private Marker marker1;
    private MapPoiPresenter mPresenter;
    private WaveView wave_map;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        FullScreenUtils.getInstance().fullScreen(MapPoiActvity.this,true);
        setContentView(R.layout.activity_map_poi_view);
        mapView = (MapView) findViewById(R.id.map_poi);
        mapView.onCreate(savedInstanceState);//此方法必须重写
        wave_map = (WaveView) findViewById(R.id.wave_map);
        findViewById(R.id.base_back_dingwei).setOnClickListener(this);
        wave_map.setBackgroundColor(Color.parseColor("#FF512F"));
        wave_map.getBackground().setAlpha(60);
        wave_map.start();
        initMapView();
        mPresenter = new MapPoiPresenter(this);
        SetPersenter(mPresenter);
        mPresenter.getMapPoiList("36.03","103.40");
    }
    private void initMapView() {
        if (aMap == null) {
            MapsInitializer.updatePrivacyAgree(MapPoiActvity.this,true);
            MapsInitializer.updatePrivacyShow(MapPoiActvity.this,true,true);
            aMap = mapView.getMap();
            setUpMap();
            UiSettings uiSettings = aMap.getUiSettings();
            uiSettings.setLogoBottomMargin(-50);//隐藏logo
        }
        mSensorHelper = new SensorEventHelper(this);
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }
    }
    private void setUpMap() {
        mUpdata = CameraUpdateFactory.newCameraPosition(
                //15是缩放比例，0是倾斜度，30显示比例
                new CameraPosition(latLng, 15, 0, 30));//这是地理位置，就是经纬度。
        aMap.moveCamera(mUpdata);//定位的方法

    }
    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper.setCurrentMarker(null);
            mSensorHelper = null;
        }
        mapView.onPause();
        deactivate();
        mFirstFix = false;
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if(null != mlocationClient){
            mlocationClient.onDestroy();
        }
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                LatLng location = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                if (!mFirstFix) {
                    mFirstFix = true;
                    addCircle(location, amapLocation.getAccuracy());//添加定位精度圆
                    addMarker(location);//添加定位图标
                    mSensorHelper.setCurrentMarker(mLocMarker);//定位图标旋转
                } else {
                    mCircle.setCenter(location);
                    mCircle.setRadius(amapLocation.getAccuracy());
                    mLocMarker.setPosition(location);
                }
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 18));
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr",errText);
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            try {
                mlocationClient = new AMapLocationClient(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }
    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }
    private void addCircle(LatLng latlng, double radius) {
        CircleOptions options = new CircleOptions();
        options.strokeWidth(1f);
        options.fillColor(FILL_COLOR);
        options.strokeColor(STROKE_COLOR);
        options.center(latlng);
        options.radius(radius);
        mCircle = aMap.addCircle(options);
    }
    private void addMarker(LatLng latlng) {
        if (mLocMarker != null) {
            return;
        }
        BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.red_nav_bg);
        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        mLocMarker = aMap.addMarker(options);
        mLocMarker.setTitle(LOCATION_MARKER_FLAG);
    }
    private void addMarkersToMap(LatLng latlng) {
        markerOption = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.pzy_nav_bg))
                .position(latlng)
                .draggable(true);
        marker1 = aMap.addMarker(markerOption);
        marker1.showInfoWindow();
        // marker旋转90度
        marker1.setRotateAngle(0);
    }
    @Override
    public void getMapPoiList(MapPoiListBean maplist) {
        if (maplist.getCode()== ConstantStaticUrl.SUCCESS_CODE){
            if (maplist.getData() != null && maplist.getData().size() > 0) {
                for (MapPoiListBean.MapPoiListBeanData  camera : maplist.getData()) {
                    for (MapPoiListBean.MapPoiListBeanData.MapPoiListBeanDataPzvos mapPoi: camera.getPzvos()) {
                        LatLng latlng = new LatLng(Double.parseDouble(mapPoi.getLatitude()), Double.parseDouble(mapPoi.getLongitude()));
                        addMarkersToMap(latlng);// 往地图上添加marker
                    }
                    markerOption = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.red_nav_bg))
                            .position(latLng)
                            .title("有" + camera.getPzvos().size() + "位陪诊员在线,预计6分钟内等待接单")
                            .draggable(true);
                    marker1 = aMap.addMarker(markerOption);
                    marker1.showInfoWindow();
                    // marker旋转90度
                    marker1.setRotateAngle(0);
                }
            } else {
                ToastUtil.showToastINFO(MapPoiActvity.this, maplist.getMsg());
            }
        }
    }
    @Override
    public void SetPersenter(Object persenter) {}
    @Override
    public void OnShowErrorMsg(String mErrorMsg) {
        ToastUtil.showToastERROR(MapPoiActvity.this,mErrorMsg);
    }
    @Override
    public void onClick(View v) {
        finishAfterTransition();
    }
}
